<template>
  <div>
    <hr>
    <h4 class="form-header h4">基本信息</h4>
    <div style="float: left">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="客户名称"
                      prop="customerId">
          <el-select v-model="queryParams.customerId"
                     placeholder="请选择客户"
                     @change="getCustomer()"
                     clearable
                     :style="{width: '100%'}">

            <el-option label="请选择" value=""></el-option>
            <el-option v-for="(item, index) in customersList"
                       :key="index"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="">-->
<!--          <el-select v-model="queryParams.state" placeholder="请选择订单状态">-->
<!--            <el-option label="已出货" :value="0"></el-option>-->
<!--            <el-option label="待出货" :value="1"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="" prop="totalAmount">
          <el-input
              v-model="queryParams.totalAmount"
              placeholder="请输入总金额"
              clearable
              @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery('queryForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div style="clear: both">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
          >新增
          </el-button>
        </el-col>
<!--        <el-col :span="1.5">-->
<!--          <el-button-->
<!--              type="success"-->
<!--              plain-->
<!--              icon="el-icon-edit"-->
<!--              size="mini"-->
<!--              :disabled="single"-->
<!--              @click="handleUpdate"-->
<!--          >修改-->
<!--          </el-button>-->
<!--        </el-col>-->
        <el-col :span="1.5">
          <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
          >删除
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </div>

    <div>
      <h4>销售订单信息</h4>
      <el-table v-loading="loading" :data="ordersList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="订单ID" align="center" prop="id"/>
        <el-table-column label="客户名称" align="center" prop="name"/>
        <el-table-column label="下单日期" align="center" prop="orderDate"/>
<!--        <el-table-column label="订单状态" align="center">-->
<!--          <template #default="scope">-->
<!--            <div v-if="scope.row.state=='1'">-->
<!--              <el-tag type="danger">待发货</el-tag>-->
<!--            </div>-->
<!--            <div v-else-if="scope.row.state=='0'">-->
<!--              <el-tag type="success">已发货</el-tag>-->
<!--            </div>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column label="订单明细" align="center" width="300px">
          <template slot-scope="scope">
            <table>
              <tr>
                <th>序号</th>
                <th>产品名称</th>
                <th>单价</th>
                <th>份数</th>
                <th>小计（元）</th>
              </tr>
              <tr v-for="(detail,index) in scope.row.salesOrderDetailsVo" :key="index">
                <td>{{ index + 1 }}</td>
                <!--商品名称-->
                <td>{{ detail.name }}</td>
                <!--商品单价-->
                <td>{{ detail.price }}</td>
                <!--份数-->
                <td>{{ detail.quantity }}</td>
                <!--小计-->
                <td>{{ detail.price * detail.quantity }}</td>
              </tr>
            </table>

          </template>
        </el-table-column>
        <el-table-column label="总金额" align="center" prop="totalAmount"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
                v-if="scope.row.status==0"
                size="mini"
                type="text"
                @click="handleUpdateStatus(scope.row)"
            >发货
            </el-button>
            <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          small
          background
          layout="prev, pager, next"
          :page-size="page.size"
          :total="page.total"
          :page-count="page.pages"
          :current-page="page.pageNo"
          @current-change="onPage"
      >
      </el-pagination>
    </div>


    <div>
      <!-- 添加或修改销售订单对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="客户"
                        prop="customerId">
            <el-select v-model="form.customerId"
                       placeholder="请选择客户"
                       @change="getCustomer()"
                       clearable
                       :style="{width: '100%'}">

              <el-option label="请选择" value=""></el-option>
              <el-option v-for="(item, index) in customersList"
                         :key="index"
                         :label="item.name"
                         :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="产品" prop="productId">
            <el-select v-model="productIds"
                       placeholder="请选择产品"
                       multiple
                       clearable
                       :style="{width: '100%'}">
              <el-option
                  v-for="(item, index) in products"
                  :key="index"
                  @click.native="changep(item)"
                  :label="item.name"
                  :value="item.id">
              </el-option>

            </el-select>

          </el-form-item>
          <el-form-item>
            <div v-for="(item,index) in plist" :key="index">
              {{ item.productName }}
              <el-input-number
                  min="1"
                  v-model="item.quantity" placeholder="请输入份数"></el-input-number>
            </div>
          </el-form-item>
          <el-form-item label="承运商"
                        prop="carrierId"
                        v-if="form.id==null"
          >
            <el-select v-model="form.carrierId"
                       placeholder="请选择承运商"
                       @change="getCarriers()"
                       clearable
                       :style="{width: '100%'}">

              <el-option label="请选择" value=""></el-option>
              <el-option v-for="(item, index) in CarriersList"
                         :key="index"
                         :label="item.name"
                         :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="下单日期" prop="orderDate">
            <el-date-picker clearable
                            v-model="form.orderDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择下单日期">
            </el-date-picker>
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  addOrders,
  delOrders,
  getCarriers,
  getCustomers,
  getOrders,
  getPage,
  listProducts,
  updateOrders
} from "@/api/salesOrders";

export default {
  name: "SalesOrdersView",
  data() {
    return {
      //承运商List
      CarriersList: [],
      // 非多个禁用
      multiple: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      //选择的数量
      plist: [],
      //选择的产品id
      productIds: [],
      //产品
      products: [],
      //客户
      customersList: [],
      // 是否显示弹出层
      open: false,
      //添加修改表单
      form: {
        id: null,
        customerId: "",
        orderDate: null,
        productId: null,
        quantity: null,
        carrierId: null,
      },
      // 表单校验
      rules: {
        customerId: [
          {required: true, message: '客户必填', trigger: 'blur'},
        ],
      },
      //修改添加标题
      title: "",
      // 销售订单表格数据
      ordersList: [],
      // 遮罩层
      loading: true,
      //分页条件
      page: {
        size:0,
        pages:0,
        pageNum: 1,
        total: 0
      },
      //查询条件
      queryParams: {
        customerId: "",
        totalAmount: null,
        state: null
      },
      // 显示搜索条件
      showSearch: true,
    }
  },
  methods: {
    /**获取承运商*/
    getCarriers() {
      getCarriers()
          .then(ref => {
            this.CarriersList = ref.data
          })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let id = row.id || this.ids
      this.$confirm('是否确认删除销售订单编号为' + id + '的数据项？', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delOrders(id)
            .then(ref => {
              if (ref.code === 200) {
                this.$message.success(ref.mess)
                this.getList();
              } else {
                this.$message.success(ref.mess)
              }
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate() {
      this.reset();
      let orderId = this.ids
      getOrders(orderId).then(res => {
        if (res.data.state == 1) {
          this.form = res.data;
          this.open = true;
          this.title = "修改销售订单";
          console.log(this.form)
        } else {
          this.$message.error("订单已发货,不可修改")
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.salesOrderDetailsDto = this.plist
          if (this.form.id != null) {
            updateOrders(this.form).then(res => {
              res.code == 200 ? this.$message.success(res.mess) : this.$message.error(res.mess)
              this.open = false;
              this.getList();
            });
          } else {
            console.log(this.form)
            addOrders(this.form).then(res => {
              res.code == 200 ? this.$message.success(res.mess) : this.$message.error(res.mess)
              this.open = false;
              this.getList();
            });
          }
          this.reset();
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      // this.CarriersList=[]
      this.plist = []
      this.productIds = []
      this.form = {
        orderId: null,
        customerId: null,
        orderDate: null,
        shippingDate: null,
        status: null,
        totalAmount: null,
        carrierId: null,
      };
      // this.$refs["form"].resetFields();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加销售订单";
    },
    changep(t) {
      setTimeout(() => {
        let s = '';
        for (let i = 0; i < this.plist.length; i++) {
          s += '[' + this.plist[i] + ']';
        }
        console.log(s)
        if (s.indexOf('[' + t.id + ']') == -1) {
          let o = {productId: t.id, productName: t.name, quantity: ''};
          this.plist.push(o)
        }
      }, 200)
    },
    //查询产品信息
    getCustomer() {
      this.$forceUpdate();
      let customerId = this.form.customerId
      this.products = [];
      this.productIds = []
      this.plist = []
      if (customerId) {
        listProducts(null).then(res => {
          this.products = res.data;
        })
      } else {
        this.products = [];
      }
    },
    getProducts() {
      listProducts(null).then(res => {
        this.products = res.data;
      })
    },
    /** 获取all客服信息*/
    getCustomers() {
      getCustomers()
          .then(res => {
            this.customersList = res.data
          })
    },
    /** 重置按钮操作 */
    resetQuery(formName) {
      this.$refs[formName].resetFields();
      this.queryParams = {
        customerId: "",
        totalAmount: null,
        state: null
      },
          this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.page.pageNum = 1;
      this.getList();
    },
    /** 换页*/
    onPage(current) {
      this.page.pageNum = current
      this.getList()
    },
    getList() {
      getPage(this.queryParams, this.page.pageNum)
          .then((res) => {
            console.log(res)
            this.ordersList = res.data.records
            this.page.total = res.data.total;
            this.page.pageNum = res.data.current;
            this.page.pages = res.data.pages;
            this.page.size = res.data.size;
            this.loading = false
          })
    }
  },
  mounted() {
    this.getList();
    this.getCustomers();
    this.getProducts();
    this.getProducts();
    this.getCarriers()
  }
}
</script>

<style scoped>

</style>
